package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.apis.article.IArticleClient;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.utils.tess4j.Tess4jClient;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmSensitiveMapper;
import com.heima.wemedia.service.WmChannelService;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.service.WmUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author げっしょく
 * @date 2021/11/23
 */

@Service
@Slf4j
@Transactional
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {

    @Autowired
    private WmNewsService wmNewsService;

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private IArticleClient iArticleClient;

    /**
     * 自媒体文章审核
     * @param id 自媒体文章id
     */
    @Async
    @Override
    public void autoScanWmNews(Integer id) {
        //根据id查询数据库
        WmNews wmNews = wmNewsService.getById(id);
        if (wmNews == null) {
            throw new RuntimeException("WmNewsAutoScanServiceImpl-文章不存在");
        }
        //获得数据的标题  内容  图片
        String title = wmNews.getTitle();
        String content = wmNews.getContent();
        String image = wmNews.getImages();
        List<Map> maps = JSONArray.parseArray(content, Map.class);
        List<String> contents = new ArrayList<>();
        List<String> conImages = new ArrayList<>();
        for (Map map : maps) {
            String type = (String) map.get("type");
            if (StringUtils.isNotEmpty(type) && type.equals("image")) {
                String value = (String) map.get("value");
                conImages.add(value);
            } else if (StringUtils.isNotEmpty(type) && type.equals("text")) {
                String text = map.get("value").toString();
                contents.add(text);
            }
        }
        //看文章中是否有敏感词
        String c = StringUtils.join(contents, ",");
        boolean isSensitive = handleSensitiveScan(c, wmNews);

        //对标题和正文进行审核
        //解析文案的数据
        String con = StringUtils.join(contents, ",");
        con = con + "," + title;
        boolean isTextScan = handleTextScan(con, wmNews);
        if (!isTextScan) {
            return;
        }

        //对图片进行审核和将多个封面图片分割成为一个数组
        boolean isImageScan = handleImageScan(image, conImages, wmNews);
        if (!isImageScan) {
            return;
        }

        //在app的文章中进行保存
        ResponseResult responseResult = saveAppArticle(wmNews);
        if (responseResult.getData().equals(200)) {
            throw new RuntimeException("WmNewsAutoScanServiceImpl-文章审核，保存app端相关文章数据失败");
        }


        //更改表中对应字段
        Long data = (Long) responseResult.getData();
        wmNews.setArticleId(data);
        updateWmNews(wmNews, (short) 9, "审核成功");


    }

    @Autowired
    private WmSensitiveMapper wmSensitiveMapper;

    /**
     * 判断文章和标题中是否包含敏感词
     * @param content
     * @param wmNews
     * @return
     */
    private boolean handleSensitiveScan(String content, WmNews wmNews) {
        boolean flag = true;
        LambdaQueryWrapper<WmSensitive> lam = new LambdaQueryWrapper();
        //查询所有的敏感词,其他的不需要
        LambdaQueryWrapper<WmSensitive> select = lam.select(WmSensitive::getSensitives);
        List<WmSensitive> wmSensitives = wmSensitiveMapper.selectList(lam);
        List<String> list = wmSensitives.stream().map(item -> item.getSensitives()).collect(Collectors.toList());

        SensitiveWordUtil.initMap(list);

        Map<String, Integer> map = SensitiveWordUtil.matchWords(content);
        if (map.size() > 0) {
            updateWmNews(wmNews, (short) 2, "文章中存在违规内容");
            flag = false;
        }
        return flag;

    }

    @Autowired
    private WmUserService wmUserService;

    @Autowired
    private WmChannelService wmChannelService;
    /**
     * 将文章数据在app端保存
     * @param wmNews
     * @return
     */
    private ResponseResult saveAppArticle(WmNews wmNews) {
        ArticleDto dto = new ArticleDto();
        BeanUtils.copyProperties(wmNews, dto);
        //获取作者id和作者名称
        //Integer userId = WmThreadLocalUtil.getThread().getId();
        Integer userId = wmNews.getUserId();
        dto.setAuthorId(Long.valueOf(userId));
        WmUser wmUser = wmUserService.getById(userId);
        if (wmUser != null) {
            dto.setAuthorName(wmUser.getName());
        }
        //获取频道名称
        WmChannel wmChannel = wmChannelService.getById(wmNews.getChannelId());
        if (wmChannel != null) {
            dto.setChannelName(wmChannel.getName());
        }
        //获取文章布局
        dto.setLayout(wmNews.getType());
        //设置文章id
        if (wmNews.getArticleId() != null) {
            dto.setId(Long.valueOf(wmNews.getArticleId()));
        }
        //设置创建时间
        dto.setCreatedTime(new Date());
        return iArticleClient.saveArticle(dto);
    }

    @Autowired
    private GreenImageScan greenImageScan;

    @Autowired
    private Tess4jClient tess4jClient;
    /**
     * 对图片进行审核
     * @param image 封面图片
     * @param conImages  正文图片
     * @param wmNews
     * @return
     */
    private boolean handleImageScan(String image, List<String> conImages, WmNews wmNews) {
        boolean flag = true;
        String[] split = image.split(",");
        conImages.addAll(Arrays.asList(split));
        if (conImages == null || conImages.size() == 0) {
            return flag;
        }
        //对图片url中相同的进行去重
        conImages = conImages.stream().distinct().collect(Collectors.toList());
        List<byte[]> list = new ArrayList<>();
        try {
            for (String conImage : conImages) {
                byte[] bytes = fileStorageService.downLoadFile(conImage);

                //将一个byte数组转换成ButteredImage
                ByteArrayInputStream bt = new ByteArrayInputStream(bytes);
                BufferedImage read = ImageIO.read(bt);

                //提取图片中的文字并且判断是否有文字
                String text = tess4jClient.doOCR(read);
                if (StringUtils.isNotEmpty(text)) {
                    //使用tess4j来识别图片中的文字
                    //审核图片文本中是否有敏感词
                    boolean b = handleSensitiveScan(text, wmNews);
                    if (!b) {
                        return b;
                    }
                }


                list.add(bytes);
            }
            Map map = greenImageScan.imageScan(list);
            if (map.get("suggestion").equals("block")) {
                flag = false;
                updateWmNews(wmNews, (short)2, "图片中有违法数据");
            } else if (map.get("suggestion").equals("review")) {
                flag = false;
                updateWmNews(wmNews, (short)3, "请人工进行审核");
            }
        } catch (Exception e) {
            flag = false;
            e.printStackTrace();
        }
        return flag;
    }

    @Autowired
    private GreenTextScan greenTextScan;
    /**
     * 对标题和文本进行审核
     * @param con
     * @param wmNews
     * @return
     */
    private boolean handleTextScan(String con, WmNews wmNews) {
        boolean flag = true;
        if (StringUtils.isEmpty(con)) {
            return flag;
        }
        Map map = null;
        try {
            map = greenTextScan.greeTextScan(con);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        if (map.get("suggestion").equals("block")) {
            flag = false;
            updateWmNews(wmNews, (short) 2, "文章内容违规");
        } else if (map.get("suggestion").equals("review")) {
            flag = false;
            updateWmNews(wmNews, (short) 3, "请转为人工审核");
        }

        return flag;
    }

    /**
     * 修改状态对数据库的内容进行修改
     * @param wmNews
     * @param status
     * @param reason
     */
    private void updateWmNews(WmNews wmNews, short status, String reason) {
        wmNews.setStatus(status);
        wmNews.setReason(reason);
        wmNewsService.updateById(wmNews);
    }
}
